<?php

namespace app\office\controller;

use PHPExcel_Writer_Excel2007;
use think\Controller;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\response\Json;

/**
 * 管理活动类
 */
class Activity extends Controller{
    public function ActivityList(){
        return $this->fetch('activity/ActivityList');
    }

    /**
     * 获取活动信息的接口
     */
    public function ActivityListJson(): Json
    {

        //获取安全码
        $SafeCode=cookie('SafeCode');

        //获取我的学院名称
        $myCollege=db('users')->where('SafeCode',$SafeCode)->value('college');

        try {
            $activityData = db('activity')->alias('a')
                ->leftJoin('wyz_users u', 'a.uid=u.Id')
                ->leftJoin('wyz_college c', 'a.college_id=c.Id')
                ->field('a.*,u.name as creator,c.college_name')
                ->where('c.college_name', $myCollege)
                ->select();
        }catch (Exception $e) {

            //返回错误信息
            return json(['result'=>'error','msg'=>'数据库错误']);
        }



        //使用循环更改查出来的步骤的值，生成字符串，减轻前端压力
        foreach($activityData as $key=>$activityDatum){
            if($activityDatum['common']=='1'){
                switch ($activityDatum["step"]){
                    case '1':
                        $activityData[$key]["step"]="待完成活动方案";
                        break;
                    case '2':
                        $activityData[$key]["step"]="待收集人员信息";
                        break;
                    case '3':
                        $activityData[$key]["step"]="待完成申报表";
                        break;
                    case '4':
                        $activityData[$key]["step"]="活动待开展";
                        break;
                    case '5':
                        //同时进行补录或者生成时长，由参与者填写
                        $activityData[$key]["step"]="待生成时长表";
                        break;
                    case '6':
                        $activityData[$key]["step"]="待完成反馈表";
                        break;
                    case '7':
                        $activityData[$key]["step"]="活动完成";
                        break;
                }
            }else{
                switch ($activityDatum["step"]){
                    case '1':
                        $activityData[$key]["step"]="待收集人员信息";
                        break;
                    case '2':
                        $activityData[$key]["step"]="待完成志愿汇登记表";
                        break;
                    case '3':
                        $activityData[$key]["step"]="活动待开展";
                        break;
                    case '4':
                        //同时进行补录或者生成时长，由参与者填写
                        $activityData[$key]["step"]="待生成时长表";
                        break;
                    case '5':
                        $activityData[$key]["step"]="活动完成";
                        break;
                }
            }
        }


        //返回查询数据
        return json($activityData);
    }

    /**
     * @return mixed 创建新活动的页面
     */
    public function AddNewActivity(){
       return $this->fetch('activity/AddNewActivity');
    }

    /**
     * 进行新活动创建的操作
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function doAddNewActivity(){

        $SafeCode=cookie('SafeCode');

        $UserData=db('users')->field('college,Id')->where('SafeCode',$SafeCode)->find();

        $college_id=db('college')->where('college_name',$UserData['college'])->value('Id');


        $validity=[
            "name",
            "comment",
            "toAll",
            "common",
            "location",
            "activity_time"
        ];

        //获取输入
        $input=input('post.');

        //只保留合法输入
        $insert=[];
        $insert["college_id"]=$college_id;
        $insert["uid"]=$UserData["Id"];
        $insert["time"]=date("Y-m-d H:i:s",time());
        foreach ($validity as $item){
            $insert[$item]=$input[$item];
        }

        try {
            db('activity')->insert($insert);

            $this->success("添加成功");

        }catch (Exception $e){
            $this->error($e->getMessage());
        }


    }

    /**
     * 修改活动信息接口
     */
    public function EditActivityJson(): Json
    {

        $validity=[
            "name",
            "comment",
            "location",
            "activity_time"
        ];

        //获取输入
        $input=input('post.');

        //获取修改的字段名
        $field=$input['field'];

        //验证输入，去除不合法的输入，防止破坏数据库
        if (!in_array($field,$validity)){

            return json([
                'result'=>'error',
                'msg'=>'字段名错误'
            ]);

        }

        //TODO 验证权限，因为赶工，暂时不验证，学校内部系统使用应该问题不大

        //尝试更新信息
        try {

            db('activity')->where('Id', $input['Id'])->update([
                $field => $input[$field]
            ]);

        }catch (Exception $e) {

            return json([
                'result'=>'error',
                'msg'=>'数据库错误'
            ]);

        }

        return json([
            'result'=>'success',
            'msg'=>'更新成功'
        ]);

    }

    /**
     * 返回活动管理页面
     * @throws Exception
     */
    public function manageActivity(){

        $ActivityId=input('get.Id');

        $ActivityData=db('activity')->alias('a')
            ->leftJoin('wyz_college c','c.Id=a.college_id')
            ->field('a.*,c.college_name')->where('a.Id',$ActivityId)->find();

        $this->assign('Id',$ActivityId);
        $this->assign('completed','false');
        $this->assign('click','false');
        $this->assign('college',$ActivityData["college_name"]);


        //是否常规活动
        if($ActivityData["common"]=="1"){
            switch ($ActivityData["step"]){
                case "1":
                    //第一步，填写活动方案
                    $url="stepOne";
                    $this->assign('stepName','填写活动方案');
                    break;
                case "2":
                    //第二步，邀请志愿者报名，可以手动停止报名，停止则进入下一步
                    $url="doStepTwo";
                    $this->assign('stepName','截止报名');
                    $this->assign('click','true');
                    break;
                case "3":
                    //第三部，填写申报表
                    $url="stepThree";
                    $this->assign('stepName','填写申报表');
                    break;
                case '4':
                    //第四步，开展活动
                    $url="doStepFour";
                    $this->assign('stepName','活动已开展');
                    $this->assign('click','true');
                    break;
                case '5':
                    //第五步，生成两表
                    $url="doStepFive";
                    $this->assign('stepName','生成时长表和补录表');
                    $this->assign('click','true');
                    break;
                case '6':
                    //第六步，填写反馈表
                    $url="stepSix";
                    $this->assign('stepName','填写反馈表');
                    break;
                case '7':
                    //无第七步
                    $url="";
                    $this->assign('stepName','');
                    $this->assign('completed','true');
                    break;

            }
        }else{
            switch ($ActivityData["step"]){
                case '1':
                    //非常规活动，第一步，完成收集人员信息
                    $url="doStepTwo";
                    $this->assign('stepName','截止报名');
                    $this->assign('click','true');
                    break;
                case '2':
                    //非常规活动，第二步，填写登记表
                    $url="uncommonStepTwo";
                    $this->assign('stepName','填写登记表');
                    break;
                case '3':
                    //非常规活动，第三步，开展活动
                    $url="doStepFour";
                    $this->assign('stepName','活动已开展');
                    $this->assign('click','true');
                    break;
                case '4':
                    //非常规活动，第四步,生成时长表和补录表
                    $url="doStepFive";
                    $this->assign('stepName','生成双表');
                    $this->assign('click','true');
                    break;
                case '5':
                    //非常规活动无需填写活动反馈表，直接结束
                    $url="";
                    $this->assign('stepName','');
                    $this->assign('completed','true');
                    break;
            }
        }

        //当前的活动类别（是否常规活动）
        $this->assign("common",$ActivityData["common"]);
        //当前的步骤
        $this->assign("step",$ActivityData["step"]);
        //当前步骤的操作链接
        $this->assign('url',$url."?Id=".$ActivityId);

        //TODO 活动管理页面需要包含步骤链接，已完成的文件下载。。。

        return $this->fetch('');


    }

    /**
     * 常规活动
     * 第一步是创建活动方案
     * @return mixed 第一步的页面
     */
    public function stepOne(){
        //TODO 权限验证

        //获取活动编号
        $ActivityId=input('param.Id');

        //获取当前活动的步骤
        $ActivityData=db('activity')->where('Id',$ActivityId)->find();

        //常规活动，判断是不是第一步
        if($ActivityData['step'] != 1 && $ActivityData["common"] == 1){
            $this->error('当前活动还未到当前步骤');
        }

        if( $ActivityData["common"] != 1){
            $this->error('非常规活动无需填写活动方案');
        }

        $this->assign('Id',$ActivityId);

        return $this->fetch('activity/stepOne');

    }


    /**
     * 第一步
     * 填写活动方案
     * @throws Exception
     */
    public function doStepOne(){
        $Id=input("param.Id");
        $data=input('post.');

        $ActivityData=db('activity')->alias('a')
            ->leftJoin('wyz_college c','c.Id=a.college_id')
            ->field('a.*,c.college_name')
            ->where('a.Id',$Id)->find();
        $data["name"]=$ActivityData["name"];
        $data["college"]=$ActivityData["college_name"];

        //获取时间
        $data["Y"]=date("Y",time());
        $data["M"]=date("m",time());
        $data["D"]=date("d",time());

        //更新活动地点
        $data["地点"]=$ActivityData["location"];

        //开启事务
        db()->startTrans();
        try{


            //循环插入
            foreach ($data as $key=>$datum){

                //换行符替换成word专属的换行符
                $datum=str_replace(["\r\n", "\r", "\n"],"<w:br/>    ",$datum);

                db('word_data')->insert([
                    'template_id'=>'1',
                    'activity_id'=>$Id,
                    'name'=>$key,
                    'value'=>$datum
                ]);
            }


            //操作完成，活动步骤变为2
            db('activity')->where('Id',$Id)->update([
               'step'=>'2'
            ]);

            $this->success("操作成功","manageActivity?Id=".$Id);
        }catch (Exception $e){
            db()->rollback();
            print_r($e->getMessage());
            $this->error('操作失败',"stepOne?Id=".$Id);
        }

    }

    /**
     * 常规活动第二步，非常规活动第一步
     * 收集人员信息，这一步不需要一个全新的页面，只需要一个接口
     * @return Json 操作结果
     */
    public function doStepTwo(): Json
    {

        //获取活动Id
        $Id=input("param.Id");

        //获取当前步骤
        $ActivityData=db('activity')->where('Id',$Id)->find();

        //不是常规活动的第二步
        if($ActivityData["common"]==1 && $ActivityData["step"]!='2'){
            return json(['result'=>'error','msg'=>'当活动无法进行此步骤']);
        }

        //不是非常规活动的第一步
        if($ActivityData["common"] != 1 && $ActivityData["step"]!='1'){
            return json(['result'=>'error','msg'=>'当活动无法进行此步骤']);
        }

        try {

            if ($ActivityData["common"]==1){
                db('activity')->where('Id', $Id)->update(['step'=>'3']);
            }else{
                db('activity')->where('Id', $Id)->update(['step'=>'2']);
            }


            return json(['result'=>'success']);
        }catch (Exception $e) {
            return json(['result'=>'error','msg'=>$e->getMessage()]);
        }

    }

    /**
     *
     * TODO 非常规活动第二步
     * TODO 填写志愿汇登记表
     * @return mixed
     * @throws
     */
    public function uncommonStepTwo(){

        //获取活动编号
        $ActivityId=input('param.Id');

        //获取当前活动的步骤
        $ActivityData=db('activity')->where('Id',$ActivityId)->find();

        //常规活动，判断是不是第一步
        if($ActivityData["common"] == 1){
            $this->error('常规活动无需填写志愿汇登记表');
        }

        //常规活动，判断是不是第一步
        if($ActivityData['step'] != 2 && $ActivityData["common"] != 1){
            $this->error('当前活动还未到当前步骤');
        }


        $this->assign('Id',$ActivityId);

        return $this->fetch('activity/uncommonStepTwo');
    }

    /**
     * 非常规活动第二步
     * 填写志愿汇登记表
     * @throws
     */
    public function doUnCommonStepTwo(){

        //获取活动Id
        $Id=input("param.Id");
        $data=input('post.');

        $ActivityData=db('activity')->alias('a')
            ->leftJoin('wyz_college c','c.Id=a.college_id')
            ->leftJoin("wyz_users u","a.uid=u.Id")
            ->field('a.*,c.college_name,u.name as username,u.qq,u.phone')
            ->where('a.Id',$Id)->find();

        //活动名称
        $data["name"]=$ActivityData["name"];

        //开办学院
        $data["college"]=$ActivityData["college_name"];

        //负责人信息
        $data["username"]=$ActivityData["username"];
        $data["phone"]=$ActivityData["phone"];
        $data["qq"]=$ActivityData["qq"];

        //志愿者人数
        $data["num"]=$ActivityData["participant_num"];

        $data["location"]=$ActivityData["location"];



        //开启事务
        db()->startTrans();
        try{


            //循环插入
            foreach ($data as $key=>$datum){

                //换行符替换成word专属的换行符
                $datum=str_replace(["\r\n", "\r", "\n"],"<w:br/>  ",$datum);

                db('word_data')->insert([
                    //TODO 这边跟着数据库改
                    'template_id'=>'4',
                    'activity_id'=>$Id,
                    'name'=>$key,
                    'value'=>$datum
                ]);
            }


            //操作完成，活动步骤变为3
            db('activity')->where('Id',$Id)->update([
                'step'=>'3'
            ]);

            $this->success("操作成功","manageActivity?Id=".$Id);
        }catch (Exception $e){
            db()->rollback();
            print_r($e->getMessage());
            $this->error('操作失败',"unCommonStepTwo?Id=".$Id);
        }
    }


    /**
     * 第三步页面
     * @return mixed
     * @throws
     */
    public function stepThree(){

        //获取活动编号
        $ActivityId=input('param.Id');

        //获取当前活动的步骤
        $step=db('activity')->where('Id',$ActivityId)->value('step');

        //获取当前活动的步骤
        $ActivityData=db('activity')->where('Id',$ActivityId)->find();

        //常规活动，判断是不是第一步
        if($ActivityData['step'] != 3 && $ActivityData["common"] == 1){
            $this->error('当前活动还未到当前步骤');
        }

        if( $ActivityData["common"] != 1){
            $this->error('非常规活动无需填写申报表');
        }

        $this->assign('Id',$ActivityId);

        return $this->fetch('activity/stepThree');
    }

    /**
     * 第三步，填写活动申报表
     * @throws
     */
    public function doStepThree(){

        //获取活动Id
        $Id=input("param.Id");
        $data=input('post.');

        $ActivityData=db('activity')->alias('a')
            ->leftJoin('wyz_college c','c.Id=a.college_id')
            ->leftJoin("wyz_users u","a.uid=u.Id")
            ->field('a.*,c.college_name,u.name as username,u.phone')
            ->where('a.Id',$Id)->find();

        //活动名称
        $data["name"]=$ActivityData["name"];

        //开办学院
        $data["college"]=$ActivityData["college_name"];

        //获取时间
        $data["Y"]=date("Y",time());
        $data["M"]=date("m",time());
        $data["D"]=date("d",time());

        //这两个参数从数据库获取
        $data["活动时间"]=$ActivityData["activity_time"];
        $data["活动地点"]=$ActivityData["location"];

        //负责人信息
        $data["username"]=$ActivityData["username"];
        $data["phone"]=$ActivityData["phone"];

        //活动人数
        $data["num"]=$ActivityData["participant_num"];

        //让所有志愿活动类型前面加一个空格
        for($i=1;$i<=11;$i++){
            $data[(string)$i]="&#160;";
        }

        //给选中的那个活动上打个勾
        $data[$data["ActivityType"]]="√&#160;";

        //开启事务
        db()->startTrans();
        try{


            //循环插入
            foreach ($data as $key=>$datum){

                //换行符替换成word专属的换行符
                $datum=str_replace(["\r\n", "\r", "\n"],"<w:br/>  ",$datum);

                db('word_data')->insert([
                    //TODO 这边跟着数据库改
                    'template_id'=>'2',
                    'activity_id'=>$Id,
                    'name'=>$key,
                    'value'=>$datum
                ]);
            }


            //操作完成，活动步骤变为4
            db('activity')->where('Id',$Id)->update([
                'step'=>'4'
            ]);

            $this->success("操作成功","manageActivity?Id=".$Id);
        }catch (Exception $e){
            db()->rollback();
            print_r($e->getMessage());
            $this->error('操作失败',"stepThree?Id=".$Id);
        }
    }

    /**
     * 常规活动第四步，非常规活动第三步
     * 活动完成开展，此步只需一个按钮即可，所以只需要一个接口
     * @return Json
     */
    public function doStepFour(): Json
    {
        //获取活动Id
        $Id=input("param.Id");

        //获取当前步骤
        $ActivityData=db('activity')->where('Id',$Id)->find();

        if( $ActivityData["common"]=="1" && $ActivityData["step"]!='4'){
            return json(['result'=>'error','msg'=>'当前活动无法进行此步骤']);
        }

        if( $ActivityData["common"]!="1" && $ActivityData["step"]!='3'){
            return json(['result'=>'error','msg'=>'当前活动无法进行此步骤']);
        }

        try {

            if ($ActivityData["common"]==1){
                db('activity')->where('Id', $Id)->update(['step'=>'5']);
            }else{
                db('activity')->where('Id', $Id)->update(['step'=>'4']);
            }

            return json(['result'=>'success']);

        }catch (Exception $e) {
            return json(['result'=>'error','msg'=>$e->getMessage()]);
        }
    }

    /**
     * 常规活动第五步
     * 非常规活动第四步
     * <p>生成双表:志愿汇时长表，志愿汇补录表</p>
     * <p>此步只需一个按钮即可，所以只需要一个接口</p>
     * @return Json
     * @throws
     */
    public function doStepFive(): Json
    {
        //获取活动Id
        $Id=input("param.Id");

        //获取当前步骤
        $ActivityData=db('activity')->where('Id',$Id)->find();

        if( $ActivityData["common"]=="1" && $ActivityData["step"]!='5'){
            return json(['result'=>'error','msg'=>'当前活动无法进行此步骤']);
        }

        if( $ActivityData["common"]!="1" && $ActivityData["step"]!='4'){
            return json(['result'=>'error','msg'=>'当前活动无法进行此步骤']);
        }

        try {

            if ($ActivityData["common"]==1){
                db('activity')->where('Id', $Id)->update(['step'=>'6']);
            }else{
                db('activity')->where('Id', $Id)->update(['step'=>'5']);
            }


            return json(['result'=>'success']);
        }catch (Exception $e) {
            return json(['result'=>'error','msg'=>$e->getMessage()]);
        }
    }

    /**
     * 第六步，完成活动反馈表
     */
    public function stepSix(){

        //获取活动编号
        $ActivityId=input('param.Id');

        //获取当前活动的步骤
        $ActivityData=db('activity')->where('Id',$ActivityId)->find();

        //常规活动，判断是不是第一步
        if($ActivityData['step'] != 6 && $ActivityData["common"] == 1){
            $this->error('当前活动还未到当前步骤');
        }

        if( $ActivityData["common"] != 1){
            $this->error('非常规活动无需填写活动反馈');
        }

        $this->assign('Id',$ActivityId);

        return $this->fetch('activity/stepSix');

    }

    /**
     * 第六步，完成活动反馈
     */
    public function doStepSix(){
        //获取活动Id
        $Id=input("param.Id");
        $data=input('post.');

        $ActivityData=db('activity')->alias('a')
            ->leftJoin('wyz_college c','c.Id=a.college_id')
            ->leftJoin("wyz_users u","a.uid=u.Id")
            ->field('a.*,c.college_name,u.name as username,u.phone')
            ->where('a.Id',$Id)->find();

        //开办学院
        $data["college"]=$ActivityData["college_name"];

        //负责人信息
        $data["name"]=$ActivityData["username"];
        $data["phone"]=$ActivityData["phone"];

        //活动相关信息
        $data["activity_name"]=$ActivityData["name"];
        $data["activity_time"]=$ActivityData["activity_time"];
        $data["location"]=$ActivityData["location"];

        //开启事务
        db()->startTrans();
        try{


            //循环插入
            foreach ($data as $key=>$datum){

                //换行符替换成word专属的换行符
                $datum=str_replace(["\r\n", "\r", "\n"],"<w:br/>",$datum);

                db('word_data')->insert([
                    //TODO 这边跟着数据库改
                    'template_id'=>'3',
                    'activity_id'=>$Id,
                    'name'=>$key,
                    'value'=>$datum
                ]);
            }


            //操作完成，活动步骤变为7
            db('activity')->where('Id',$Id)->update([
                'step'=>'7'
            ]);

            $this->success("操作成功","manageActivity?Id=".$Id);
        }catch (Exception $e){
            db()->rollback();
            print_r($e->getMessage());
            $this->error('操作失败',"stepSix?Id=".$Id);
        }
    }

    /**
     * 获取生成的word
     */
    public function getWord(){

        //获取所需的模板名称
        $template_id=input("get.template_id");

        //获取活动名称
        $activity_id=input("get.activity_id");

        //获取对应此活动，当前文件的信息
        $wordData=db('word_data')->where([
            'template_id'=>$template_id,
            'activity_id'=>$activity_id
        ])->select();

        //获取模板信息（位置等）
        $templateData=db('word_template')->where('Id',$template_id)->find();

        //获取根目录
        $rootPath=env('root_path');

        //获取模板路径
        $filePath=$templateData['path'];


        $data=[];

        //循环来填充模板信息
        foreach ($wordData as $wordDatum){
            $data[$wordDatum["name"]]=$wordDatum["value"];
        }

        $word=new Word();

        //生成文件并返回文件名
        $fileName=$word->substitute($filePath,$data);

        $filePath='public/words/files/'.$fileName;

        $word->download($filePath,$templateData["template_name"].".docx");


    }

    /**
     * 获取excel表格
     */
    public function getExcel(){

        $type=input('get.type');
        $ActivityId=input('get.ActivityId');

        //判断查询类型，来觉得select的数据
        if ($type == 1){
            $append=0;
        }else{
            $append=1;
        }

        //活动参与信息
        $ActivityData=db('user_activity')->alias('ua')
            ->leftJoin('wyz_users u','u.Id=ua.uid')
            ->leftJoin('wyz_activity a','a.Id=ua.activity_id')
            ->leftJoin("wyz_college c","a.college_id=c.Id")
            ->leftJoin("wyz_users u2",'u2.Id=a.uid')
            ->field('c.college_name,u.*,a.location,a.activity_time,a.name as activity_name,ua.time,ua.append,u2.name as manager_name')
            ->where([
                'ua.append'=>$append,
                'a.Id'=>$ActivityId
            ])->select();

        $objPHPExcel = new \PHPExcel();
        // 设置sheet
        $objPHPExcel->setActiveSheetIndex(0);

        //合并单元格
        $objPHPExcel->getActiveSheet()->mergeCells('A1:H1');

        //设置标题字体
        $objPHPExcel->getActiveSheet()->getStyle('A1')
            ->getFont()
            ->setSize(14)
            ->setName('宋体');

        //设置字体居中
        $objPHPExcel->getActiveSheet()->getStyle('A1')
            ->getAlignment()
            ->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER)
            ->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER)
            ->setWrapText(true);

        // 设置列的宽度
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(9);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(14);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(24);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(21);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(22);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(23);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(11);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(9);


        $objPHPExcel->getActiveSheet()->SetCellValue('A2', '姓名');
        $objPHPExcel->getActiveSheet()->SetCellValue('B2', '学号');
        $objPHPExcel->getActiveSheet()->SetCellValue('C2', '身份证号');
        $objPHPExcel->getActiveSheet()->SetCellValue('D2', '活动项目');
        $objPHPExcel->getActiveSheet()->SetCellValue('E2', '活动地点');
        $objPHPExcel->getActiveSheet()->SetCellValue('F2', '活动时间');
        $objPHPExcel->getActiveSheet()->SetCellValue('G2', '活动时长');
        $objPHPExcel->getActiveSheet()->SetCellValue('H2', '证明人');
        //存取数据
        $num = 3;
        foreach ($ActivityData as $key => $value) {

            $objPHPExcel->getActiveSheet()->SetCellValue('A' . $num, ' '.$value['name']);
            $objPHPExcel->getActiveSheet()->SetCellValue('B' . $num, ' '.$value['sid']);
            $objPHPExcel->getActiveSheet()->SetCellValue('C' . $num, ' '.$value['identity_card']);
            $objPHPExcel->getActiveSheet()->SetCellValue('D' . $num, ' '.$value["activity_name"]);
            $objPHPExcel->getActiveSheet()->SetCellValue('E' . $num, ' '.$value["location"]);
            $objPHPExcel->getActiveSheet()->SetCellValue('F' . $num, ' '.$value["activity_time"]);
            $objPHPExcel->getActiveSheet()->SetCellValue('G' . $num, ' '.$value['time']);
            $objPHPExcel->getActiveSheet()->SetCellValue('H' . $num, ' '.$value['manager_name']);
            $num++;
        }

        //活动信息
        $ActivityDetail=db('activity')->alias('a')
            ->leftJoin("wyz_college c","a.college_id=c.Id")
            ->field('a.name as activity_name,c.college_name')
            ->where([
                'a.Id'=>$ActivityId
            ])->find();

        //如果表类型为志愿汇收集表
        if ($type == 1){
            $fileName = $ActivityDetail["college_name"].$ActivityDetail["activity_name"]."志愿时长表";
        }else{
            //如果为志愿汇补录表
            $fileName = $ActivityDetail["college_name"].$ActivityDetail["activity_name"]."志愿时长补录表";
        }
        // 设置表头
        $objPHPExcel->getActiveSheet()->SetCellValue('A1', $fileName);

        //
        $xlsName = iconv('utf-8', 'gb2312', $fileName);
        // 设置工作表名
        $objPHPExcel->getActiveSheet()->setTitle('sheet');
        //下载 excel5与excel2007
        $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
        ob_end_clean();     // 清除缓冲区,避免乱码
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate,post-check=0,pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl;charset=UTF-8");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header("Content-Disposition:attachment;filename=" . $xlsName . ".xlsx");
        header("Content-Transfer-Encoding:binary");
        $objWriter->save("php://output");


    }


}


